package com.hjg.baseglide;


import java.util.concurrent.LinkedBlockingQueue;

public class RequestManager {

    private static RequestManager requestManager;

    private RequestManager() {
        stop();
        creatAndStart();

    }

    public static RequestManager getInstance() {
        if (requestManager == null) {
            synchronized (RequestManager.class) {
                if (requestManager == null) {
                    requestManager = new RequestManager();
                }
            }
        }
        return requestManager;
    }

    //有一个队列
    private LinkedBlockingQueue<BitmapRequest> linkedBlockingQueue = new LinkedBlockingQueue();

    //加入队列
    public void addBitmapRequest(BitmapRequest bitmapRequest) {
        if (!linkedBlockingQueue.contains(bitmapRequest)) {
            linkedBlockingQueue.add(bitmapRequest);
        } else {

        }
    }

    public void stop() {
        if (bitmapDispatchers != null && bitmapDispatchers.length > 0) {
            for (BitmapDispatcher bitmapDispatcher : bitmapDispatchers) {
                bitmapDispatcher.interrupt();
            }
        }

    }


    private BitmapDispatcher[] bitmapDispatchers;

    /**
     * 创建dispatcher
     * 需要思考创建多少个，并且需要统一管理这些dispatcher
     */
    private void creatAndStart() {
        //根绝当前应用能创建实际的线程数来创建dispatcher
        int i = Runtime.getRuntime().availableProcessors();

        bitmapDispatchers = new BitmapDispatcher[i];
        for (int i1 = 0; i1 < bitmapDispatchers.length; i1++) {
            BitmapDispatcher bitmapDispatcher = new BitmapDispatcher(linkedBlockingQueue);
            bitmapDispatcher.start();
            bitmapDispatchers[i1] = bitmapDispatcher;
        }

    }


}
